package com.software.myopiachildren.ui;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.king.zxing.Intents;
import com.king.zxing.util.CodeUtils;
import com.software.myopiachildren.R;
import com.software.myopiachildren.base.BaseActivity;
import com.software.myopiachildren.bean.BaseDataInfo;
import com.software.myopiachildren.bean.BaseInfo;
import com.software.myopiachildren.content.Constant;
import com.software.myopiachildren.http.HostType;
import com.software.myopiachildren.http.HttpApi2;
import com.software.myopiachildren.utils.ToastUtil;
import com.software.myopiachildren.utils.UriUtils;
import com.software.myopiachildren.utils.eb.EB;
import com.software.myopiachildren.utils.eb.EbData;
import com.software.myopiachildren.utils.perm.NetworkUtils;
import com.software.myopiachildren.utils.sp.SP;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.Subscribe;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * 绑定设备页
 *
 * @author penglei
 * @date 2020/05/13
 */
public class BindDeviceActivity extends BaseActivity {
    private static final String TAG = "BindDeviceActivity";

    @BindView(R.id.iv_title_left)
    ImageView mIvTitleLeft;
    @BindView(R.id.tv_title_text)
    TextView mTvTitleText;
    @BindView(R.id.tv_title_right)
    TextView mTvTitleRight;
    @BindView(R.id.lay_title_home)
    LinearLayout mLayTitleHome;

    @BindView(R.id.tv_bind_status)
    TextView mTvBindStatus;
    @BindView(R.id.tv_bind_number)
    TextView mTvBindNumber;
    @BindView(R.id.tv_bind)
    TextView mTvBind;
    @BindView(R.id.ll_bind)
    LinearLayout mLlBind;


    public static final int REQUEST_CODE_SCAN = 0X01;
    public static final int REQUEST_CODE_PHOTO = 0X02;

    private int isDevice = 0;  // 0未绑定  1：已绑定
    private String deviceCode;  // 设备号

    @Override
    protected int getContentViewId() {
        return R.layout.activity_bind_device;
    }

    @Override
    public void initView() {
        EB.register(this);
        mTvTitleText.setText(getResources().getString(R.string.s_bind_device));
    }

    @Override
    public void initData() {
        getHasBinding();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    public void onDestroy() {
        EB.unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void onEvent(EbData data) {
        if (data.getType() == 10) {
            getHasBinding();
        }
    }

    @OnClick({R.id.iv_title_left, R.id.ll_bind})
    public void onClick(final View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;

            case R.id.ll_bind:
                if (isDevice == 0) {
                    getPermissions();
                } else if (isDevice == 1) {
                    getUnBindDevice();
                }

                break;
        }
    }

    /**
     * 检测权限
     */
    private void getPermissions() {
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Log.e(TAG,"权限通过");
                        //跳转自定义扫码界面
                        Intent intent = new Intent(BindDeviceActivity.this, ScanBindActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_SCAN);
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        ToastUtil.showShort("没有权限无法扫描呦");
                    }
                }).start();
    }


    /**
     * 是否有绑定设备
     */
    private void getHasBinding() {
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(BindDeviceActivity.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getHasBinding(headers).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseDataInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseDataInfo baseDataInfo) {
                            try {
                                Log.e(TAG, "===baseDataInfo:" + baseDataInfo.toString());
                                if (baseDataInfo.getCode().equals(Constant.CODE_SUCCESS)) {
//                                    ToastUtil.showShort(baseDataInfo.getMsg());
                                    if (baseDataInfo.getData().getHas_device() == 0) {
                                        isDevice = 0;
                                        mTvBindStatus.setText(getResources().getString(R.string.s_bind_device_content1));
                                        mTvBindNumber.setText("");
                                        mTvBind.setText(getResources().getString(R.string.s_bind_device_goto));
                                    } else {
                                        isDevice = 1;
                                        deviceCode = baseDataInfo.getData().getDevice_code();
                                        mTvBindStatus.setText(getResources().getString(R.string.s_onbind));
                                        mTvBindNumber.setText(baseDataInfo.getData().getDevice_code());
                                        mTvBind.setText(getResources().getString(R.string.s_bind_device_ungoto));
                                    }
                                    new SP().save(Constant.BIND_DEVICE, baseDataInfo.getData().getHas_device());
                                    new SP().save(Constant.DEVICE_CODE, baseDataInfo.getData().getDevice_code());
                                    EB.post(new EbData(11));
                                } else {
                                    ToastUtil.showShort(baseDataInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }


    /**
     * 绑定设备
     */
    private void getBindDevice(String device_code) {
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(BindDeviceActivity.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("device_code", device_code);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getBindDevice(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                    getHasBinding();
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }

    }


    /**
     * 解绑设备
     */
    private void getUnBindDevice() {
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(BindDeviceActivity.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("device_code", deviceCode);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getUnBindDevice(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                    getHasBinding();
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case REQUEST_CODE_SCAN:
                    String result = data.getStringExtra(Intents.Scan.RESULT);
                    Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
                    //验证设备号
                    if (TextUtils.isEmpty(result)) {
                        ToastUtil.showShort(getString(R.string.toast_devicenum_empty));
                        return;
                    }
                    getBindDevice(result);
                    break;
                case REQUEST_CODE_PHOTO:
                    parsePhoto(data);
                    break;
            }

        }
    }

    private void asyncThread(Runnable runnable) {
        new Thread(runnable).start();
    }

    /**
     * 识别图片
     *
     * @param data
     */
    private void parsePhoto(Intent data) {
        final String path = UriUtils.getImagePath(this, data);
        Log.d("Jenly", "path:" + path);
        if (TextUtils.isEmpty(path)) {
            return;
        }
        //异步解析
        asyncThread(new Runnable() {
            @Override
            public void run() {
                final String result = CodeUtils.parseCode(path);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("Jenly", "result:" + result);
                        Toast.makeText(BindDeviceActivity.this, result, Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });

    }

}
